package grpc

import (
	"context"
	pb "enotify/api/async"
	"enotify/pkg/async"
	"enotify/pkg/async/conf"
	"enotify/pkg/async/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"net"
	"time"
)

func New(c *conf.RPCServer, async *async.Async)  *grpc.Server {
	params := grpc.KeepaliveParams(keepalive.ServerParameters{
		MaxConnectionIdle:     time.Duration(c.IdleTimeout),
		MaxConnectionAge:      time.Duration(c.MaxLifeTime),
		MaxConnectionAgeGrace: time.Duration(c.ForceCloseWait),
		Time:                  time.Duration(c.KeepAliveInterval),
		Timeout:               time.Duration(c.KeepAliveTimeout),
	})
	srv := grpc.NewServer(params)
	lis, err := net.Listen(c.Network,c.Addr)
	if err != nil {
		panic(err)
	}
	pb.RegisterAsyncServer(srv,&server{async: async})
	go func() {
		if err := srv.Serve(lis); err != nil {
			panic(err)
		}
	}()
	return srv
}

type server struct {
	async *async.Async
}
func (s *server) Push(ctx context.Context, req *pb.AsyncReq) (*pb.AsyncReply, error)  {
	reqId, err := s.async.Push(req.BizType,req.BizId,req.Data)
	var code int32 = 0
	var msg = ""
	if err != nil {
		code = 10001
		msg = err.Error()
	}
	reply := &pb.AsyncReply{
		Code: code,
		Msg:  msg,
		Data: &pb.Body{ReqId: reqId},
	}
	return reply,nil
}
func (s *server) GetReq(ctx context.Context, req *pb.GetReq) (*pb.GetReqReply, error)  {
	reply := pb.GetReqReply{}
	if req.ReqId < 1 {
		reply.Code = 20001
		reply.Msg = errors.ErrReqId.Error()
		return &reply,nil
	}
	data, err := s.async.GetReq(req.ReqId)
	if err != nil {
		reply.Code = 10001
		reply.Msg = err.Error()
		return &reply, nil
	}
	reqReply := pb.ReqReply{
		BizType: data.BizType,
		BizId:   data.BizId,
		TypeUrl: data.TypeUrl,
		Params:  data.Data,
	}
	reply.Data = &reqReply
	return &reply, nil
}